import React, { PureComponent, Fragment } from 'react';
import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Button,
  Divider,
  Tooltip,
  Select,
} from 'antd';
import { connect } from 'dva';
import { formatMessage } from 'umi/locale';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    return <InputNumber />;
  };

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      max,
      min,
      step,
      ...restProps
    } = this.props;
    return (
      <EditableContext.Consumer>
        {form => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [
                      {
                        required: true,
                        message: `请输入${title}!`,
                      },
                    ],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : (
                restProps.children
              )}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

@connect(({ cbjt }) => ({ cbjt }))
class KnifeCutParamsForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { editingKey: '' };
    this.columns = [
      {
        title: '0 ~ 0.33 切割速度',
        dataIndex: 'speedLev1',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '1',
      },
      {
        title: '0.34 ~ 1 切割速度',
        dataIndex: 'speedLev2',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '2',
      },
      {
        title: '1.1 ~ 1.5 切割速度',
        dataIndex: 'speedLev3',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '3',
      },
      {
        title: '1.6 ~ 2 切割速度',
        dataIndex: 'speedLev4',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '4',
      },

      {
        title: '2 ~ 切割速度',
        dataIndex: 'speedLev5',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '5',
      },
      {
        title: '第一刀切割速度比率',
        dataIndex: 'firstCutRate',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '6',
      },
      {
        title: '工具切割速度',
        dataIndex: 'toolCutSpped',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '7',
      },
      {
        title: '下刀深度',
        dataIndex: 'cutDeep',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '8',
      },
      {
        title: '刀角度补偿',
        dataIndex: 'knifeAngleOffset',
        editable: true,
        width: '10%',
        inputType: 'number',
        key: '9',
      },
      {
        title: formatMessage({ id: 'app.tools.operate' }),
        key: 'action',
        width: '10%',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.saveKnifeCutParams(form, record.key)}
                        style={{ marginRight: 8 }}
                      >
                        {formatMessage({ id: 'app.tools.save' })}
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm title="确认取消吗?" onConfirm={() => this.cancel(record.key)}>
                    <a>{formatMessage({ id: 'app.tools.cancel' })}</a>
                  </Popconfirm>
                </span>
              ) : (
                <span>
                  <a onClick={() => this.edit(record.key)}>
                    {formatMessage({ id: 'app.tools.edit' })}
                  </a>
                </span>
              )}
            </div>
          );
        },
      },
    ];
  }
  isEditing = record => record.key === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  saveKnifeCutParams(form, key) {
    const { dispatch } = this.props;
    form.validateFields((error, row) => {
      console.log('row', row);
      if (error) {
        return;
      }
      const newData = { ...row, key: '1' };
      this.edit('');
      dispatch({
        type: 'cbjt/saveKnifeCutParams',
        payload: newData,
      });
    });
  }

  edit(key) {
    this.setState({ editingKey: key });
  }

  render() {
    const { knifeCutParams } = this.props.cbjt;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.inputType,
          dataIndex: col.dataIndex,
          max: col.max,
          min: col.min,
          step: col.step,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Fragment>
        <Table
          components={components}
          bordered
          dataSource={knifeCutParams}
          columns={columns}
          rowClassName="editable-row"
          size={'small'}
          pagination={false}
        />
      </Fragment>
    );
  }
}

export default KnifeCutParamsForm;
